package com.ja.util;

import java.text.*;
import java.util.Date;

/**
 * Created by 11936 on 2019/4/29.
 */
public class MyDateFormat extends DateFormat {
    private DateFormat dateFormat;
    private SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    public MyDateFormat() {
    }

    public MyDateFormat(DateFormat dateFormat) {
        this.dateFormat = dateFormat;
    }

    @Override
    public StringBuffer format(Date date, StringBuffer toAppendTo, FieldPosition fieldPosition) {
        return dateFormat.format(date, toAppendTo, fieldPosition);
    }

    @Override
    public Date parse(String source, ParsePosition pos) {
        Date date = null;
        try{
            date = simpleDateFormat.parse(source, pos);
        }catch (Exception e){
            dateFormat.parse(source, pos);
        }
        return date;
    }

    // 主要还是装饰这个方法
    @Override
    public Date parse(String source) throws ParseException {

        Date date = null;

        try {

            // 先按我的规则来
            date = simpleDateFormat.parse(source);
        } catch (Exception e) {

            // 不行，那就按原先的规则吧
            date = dateFormat.parse(source);
        }

        return date;
    }
}
